<template>
  <div class="common-layout">
    <el-container>
      <el-header class="header">
        <div>
          <span style="color: #666">账号:</span>
          <el-input
            v-model="input1"
            style="width: 240px; margin: 0 12px"
            placeholder="请输入账号"
          />
          <el-button type="primary" style="margin: 0 12px" @click="search"
            >搜索</el-button
          >
        </div>
      </el-header>
      <el-main class="main">
        <el-button type="success" @click="addUser">添加用户</el-button>
        <el-divider />
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="id" label="序号" />
          <el-table-column prop="userName" label="账号" />
          <el-table-column prop="userNickname" label="昵称" />
          <el-table-column prop="userRealname" label="真实姓名" />
          <el-table-column prop="userGender" label="性别" />
          <el-table-column prop="userBirthday" label="生日" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column prop="userProfilePictureSrc" label="头像">
            <template #default="scope">
              <!-- <img :src="avatarUrl" alt="头像" class="avatar"/> -->
              <el-image
                v-if="scope.row.userProfilePictureSrc != null"
                preview-teleported
                :src="scope.row.userProfilePictureSrc"
                style="height: 40px; width: 40px"
              />
              <el-image v-else>
                <template #error>
                  <div class="image-slot">
                    <el-icon><icon-picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="操作" label="操作">
            <template #default="scope">
              <el-button link type="primary" @click="viewUser(scope.row)">浏览</el-button>
              <el-button link type="danger" @click="deleteUser(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 用户管理对话框组件 -->
        <UserManageDialog
          v-if="dialogVisible"
          v-model="dialogVisible"
          :new-form-data="currentRow"
          :operation-type="operationType"
          @update="updateAdmin"
        />
      </el-main>
      <el-footer class="footer"
        ><div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :size="size"
            :background="background"
            layout="total, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          /></div
      ></el-footer>
    </el-container>
  </div>
</template>

<script lang="js" setup>
import { ref } from "vue";
import {  ElMessage, ElMessageBox } from "element-plus";
import instance from "@/utils/request";
import { onMounted } from "vue";
import { Picture as IconPicture } from '@element-plus/icons-vue'
// 导入用户管理对话框组件
import UserManageDialog from "@/components/user/UserManageDialog.vue";

const input1 = ref("");
const currentPage = ref(1);
const pageSize = ref(5);
const size = ref("large");
const total = ref(0);
const dialogVisible = ref(false);
const currentRow = ref({}); // 当前操作的行数据
const operationType = ref('add'); // 操作类型: view, add, edit

const search = () => {
  ElMessage.success("搜索成功！");
};

// 查看用户详情方法
const viewUser = async (row) => {
  try {
    const res = await instance.get("/user/getUserInfoById", {
      params: {
        id: row.id
      }
    });
    
    if (res.data.code === 200) {
      currentRow.value = res.data.data;
      operationType.value = 'view'; // 设置为浏览模式
      dialogVisible.value = true;
    } else {
      ElMessage.error(res.data.msg || "获取用户信息失败");
    }
  } catch (error) {
    ElMessage.error("获取用户信息时发生错误");
    console.error(error);
  }
};

// 添加用户方法
const addUser = () => {
  currentRow.value = {};
  operationType.value = 'add'; // 设置为添加模式
  dialogVisible.value = true;
};


// 添加删除用户方法
const deleteUser = (row) => {
  ElMessageBox.confirm(
    `确定要删除用户 "${row.userName}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      // 方式1: 使用 DELETE 请求，参数通过 URL 传递
      const res = await instance.delete("/user/deleteUser", {
        params: {
          id: row.id
        }
      });
      
      // 方式2: 如果后端期望使用 POST 请求，可以取消注释下面的代码并注释上面的代码
      // const res = await instance.post("/user/deleteUser", {
      //   id: row.id
      // });
      
      if (res.data.code === 200) {
        ElMessage.success("删除成功！");
        getUserList(); // 刷新用户列表
      } else {
        ElMessage.error(res.data.msg || "删除失败");
      }
    } catch (error) {
      ElMessage.error("删除用户时发生错误: " + error.message);
      console.error(error);
    }
  }).catch(() => {
    ElMessage.info("已取消删除");
  });
};

const tableData = ref([]);

// 添加用户后的更新方法
const updateAdmin = () => {
  getUserList() // 刷新用户列表
  dialogVisible.value = false // 关闭弹窗
}

onMounted(() => {
  getUserList();
});
const getUserList = async () => {
  // 在这里添加获取用户列表的逻辑
  const res = await instance.get("/user/getUserList", {
    params: {
      page: currentPage.value,
      pageSize: pageSize.value,
    },
  });
  if (res.data.code === 200) {
    tableData.value = res.data.data.records;
    total.value = res.data.data.total;
    console.log(sessionStorage.getItem("adminName"));
    console.log(sessionStorage.getItem("adminId"));
  } else {
    ElMessage.error("获取用户列表失败");
  }
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  getUserList();
}
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getUserList();
}
</script>
<style scoped>
.header {
  background-color: rgb(255, 255, 255);
  padding: 12px 20px;
  border-bottom: 1px solid #eee;
}
.main {
  background-color: rgb(255, 255, 255);
  padding: 20px 20px;
  height: calc(84vh - 100px);
  margin-top: 10px;
}
.footer {
  background-color: rgb(255, 255, 255);
  padding: 12px 20px;
  border-bottom: 1px solid #eee;
  margin-top: 15px;
}
.demo-pagination-block {
  display: flex;
  justify-content: flex-end;
}
</style>
